package com.lagou.module3.task4;

import java.util.ArrayList;

/**
 *
 * 实现存储学生节点信息
 *      提供实现增删改查以及遍历所有学生信息的功能
 *
 */
public class StudentData {

    private ArrayList<Student> head;
    private static StudentData instance = new StudentData();

    public StudentData() {
        head = new ArrayList<>();
    }

    public static StudentData getInstance(){
        return instance;
    }

    // 增加元素
    public boolean addElement(Student id){
        Student find = findElement(id.getId());
        if (find != null){
            System.out.println("已存在相同学号记录");
            System.out.println(find);
            return false;
        }
        return head.add(id);
    }
    // 查找元素
    public Student findElement(int studentNo){
        for (Student node: head){
            if (studentNo == node.getId()){
                return node;
            }
        }
        return null;
    }
    // 返回元素index位置
    public int findElementIndex(int studentNo){
        return head.indexOf(new Student("",99,studentNo));
    }
    // 修改元素
    public Student setElement(int index, Student node){
        return head.set(index, node);
    }
    // 遍历集合
    public void traverse(){
        for (Student node: head){
            System.out.println(node);
        }
    }
    // 删除元素，根据传入的学号删除元素
    public boolean removeElement(int studentNo){
        Student node = findElement(studentNo);
        if (null == node){
            System.out.println("无此学号，删除失败！");
            return false;
        }
        return head.remove(node);
    }

}
